package com.ruoyi.system.service.impl;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.domain.RecordArchives;
import com.ruoyi.system.domain.RecordArchivesBook;
import com.ruoyi.system.domain.RecordEngin;
import com.ruoyi.system.domain.vo.BarChartVo;
import com.ruoyi.system.domain.vo.UploadPath;
import com.ruoyi.system.mapper.RecordArchivesBookMapper;
import com.ruoyi.system.mapper.RecordArchivesMapper;
import com.ruoyi.system.mapper.RecordEnginMapper;
import com.ruoyi.system.mapper.RecordTypeMapper;
import com.ruoyi.system.service.IRecordArchivesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.validation.Validator;
import java.util.List;

/**
 * 案卷管理Service业务层处理
 *
 * @author admin
 * @date 2022-03-02
 */
@Service
public class RecordArchivesServiceImpl implements IRecordArchivesService {
    private static final Logger log = LoggerFactory.getLogger(RecordArchivesServiceImpl.class);
    @Autowired
    protected Validator validator;
    @Autowired
    private RecordArchivesMapper recordArchivesMapper;
    @Autowired
    private RecordArchivesBookMapper recordArchivesBookMapper;
    @Autowired
    private RecordEnginMapper recordEnginMapper;
    @Autowired
    private RecordTypeMapper recordTypeMapper;

    /**
     * 查询案卷管理
     *
     * @param archivesId 案卷管理主键
     * @return 案卷管理
     */
    @Override
    public RecordArchives selectRecordArchivesByArchivesId(String archivesId) {
        return recordArchivesMapper.selectRecordArchivesByArchivesId(archivesId);
    }

    /**
     * 查询案卷管理列表
     *
     * @param recordArchives 案卷管理
     * @return 案卷管理
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<RecordArchives> selectRecordArchivesList(RecordArchives recordArchives) {
        return recordArchivesMapper.selectRecordArchivesList(recordArchives);
    }

    // 按案卷题名查询
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<RecordArchives> selectRecordArchivesListByName(RecordArchives archives) {
        return recordArchivesMapper.selectRecordArchivesListByName(archives);
    }

    // 案卷台账查询
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<RecordArchivesBook> selectRecordArchivesListBook(RecordArchivesBook recordArchivesBook) {
        return recordArchivesBookMapper.selectRecordArchivesListBook(recordArchivesBook);
    }

    // 状态图、饼状图数据查询
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<BarChartVo> selectBarChartVoList(BarChartVo barChartVo) {
        return recordArchivesMapper.selectBarChartVoList(barChartVo);
    }

    @Override
    public String getUploadPath(Integer data) {
        // 案卷分类/工程分类ID/案卷ID，丢弃这个方案
        // 总登记号
        UploadPath uploadPath = recordArchivesMapper.getUploadPath(data);
        String folderName = uploadPath.getRegistNum();
        return folderName;
    }

    /**
     * 新增案卷管理
     *
     * @param recordArchives 案卷管理
     * @return 结果
     */
    @Override
    public int insertRecordArchives(RecordArchives recordArchives) {
        // 获取工程级分类ID的父ID，作为案卷分类ID
        RecordEngin engin = recordEnginMapper.selectRecordEnginByEnginId(recordArchives.getEnginId());
        System.out.println(engin);
        if (engin == null) { // 注意：老项目没有项目工程ID，升级整改再导入。
            throw new ServiceException("未找到ID为" + recordArchives.getEnginId() + "的项目工程");
        } else {
            String typeId = engin.getTypeId().toString();
            String parentId = recordTypeMapper.selectRecordTypeByTypeId(typeId).getParentId();
            recordArchives.setTypeId(parentId);
            // 创建人ID，用于数据权限
            recordArchives.setObjInt11(SecurityUtils.getUserId());
            recordArchives.setObjStr4(SecurityUtils.getUsername());
            recordArchives.setCreateBy(SecurityUtils.getLoginUser().getUsername());
            recordArchives.setCreateTime(DateUtils.getNowDate());
            return recordArchivesMapper.insertRecordArchives(recordArchives);
        }
    }

    /**
     * 修改案卷管理
     *
     * @param recordArchives 案卷管理
     * @return 结果
     */
    @Override
    public int updateRecordArchives(RecordArchives recordArchives) {
        recordArchives.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        recordArchives.setUpdateTime(DateUtils.getNowDate());
        return recordArchivesMapper.updateRecordArchives(recordArchives);
    }

    /**
     * 批量删除案卷管理
     *
     * @param archivesIds 需要删除的案卷管理主键
     * @return 结果
     */
    @Override
    public int deleteRecordArchivesByArchivesIds(String[] archivesIds) {
        StringBuilder failureMsg = new StringBuilder();
        try {
            return recordArchivesMapper.deleteRecordArchivesByArchivesIds(archivesIds);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("案卷已挂文件，禁止删除！");
        }
    }

    /**
     * 删除案卷管理信息
     *
     * @param archivesId 案卷管理主键
     * @return 结果
     */
    @Override
    public int deleteRecordArchivesByArchivesId(String archivesId) {
        return recordArchivesMapper.deleteRecordArchivesByArchivesId(archivesId);
    }

    @Override
    @Transactional
    public int updateArchivesApplyByIds(String[] archivesIds) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (int i = 0; i < archivesIds.length; i++) {
            RecordArchives recordArchives = new RecordArchives();
            recordArchives.setArchivesId(archivesIds[i]);
            recordArchives.setObjStr1("1"); //申请状态字段，1：申请
            RecordArchives recordArchivesOld = recordArchivesMapper.selectRecordArchivesByArchivesId(archivesIds[i]);
            if ("0".equals(recordArchivesOld.getObjStr1()) || "3".equals(recordArchivesOld.getObjStr1())) { // 未申请或拒绝状态，可申请
                int res = recordArchivesMapper.updateRecordArchives(recordArchives);
                if (res != 1) { // 更新条数为0
                    //手工回滚异常
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new ServiceException("操作失败！数据更新条数为0");
                }
            } else {
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                throw new ServiceException("只允许操作未申请和审批拒绝的案卷");
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public int updateArchivesApprove(String[] archivesIds) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (int i = 0; i < archivesIds.length; i++) {
            RecordArchives recordArchives = new RecordArchives();
            recordArchives.setArchivesId(archivesIds[i]);
            recordArchives.setObjStr1("2"); //申请状态字段,2：通过
            RecordArchives recordArchivesOld = recordArchivesMapper.selectRecordArchivesByArchivesId(archivesIds[i]);
            // 如果总登记号为0，自增+1
//            if(recordArchivesOld.getRegistNum() == 0){
//                List<RecordArchives> archList = recordArchivesMapper.selectRegistNumCount();
//                if(archList.size() != 0){
//                    recordArchives.setRegistNum(archList.get(0).getRegistNum() + 1);
//                }else {
//                    recordArchives.setRegistNum(1); // 第一次添加
//                }
//            }
            if ("1".equals(recordArchivesOld.getObjStr1())) { // 申请中状态，可审批
                int res = recordArchivesMapper.updateRecordArchives(recordArchives);
                if (res != 1) { // 更新条数为0
                    //手工回滚异常
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new ServiceException("操作失败！数据更新条数为0");
                }
            } else {
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                throw new ServiceException("只允许操作申请中的案卷");
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public int updateArchivesReject(String[] archivesIds) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (int i = 0; i < archivesIds.length; i++) {
            RecordArchives recordArchives = new RecordArchives();
            recordArchives.setArchivesId(archivesIds[i]);
            recordArchives.setObjStr1("3"); //申请状态字段，3：拒绝
            RecordArchives recordArchivesOld = recordArchivesMapper.selectRecordArchivesByArchivesId(archivesIds[i]);
            // 如果总登记号为0，自增+1
//            if(recordArchivesOld.getRegistNum() == 0){
//                List<RecordArchives> archList = recordArchivesMapper.selectRegistNumCount();
//                if(archList.size() != 0){
//                    recordArchives.setRegistNum(archList.get(0).getRegistNum() + 1);
//                }else {
//                    recordArchives.setRegistNum(1); // 第一次添加
//                }
//            }
            if ("1".equals(recordArchivesOld.getObjStr1())) { // 申请中状态，可审批
                int res = recordArchivesMapper.updateRecordArchives(recordArchives);
                if (res != 1) { // 更新条数为0
                    //手工回滚异常
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new ServiceException("操作失败！数据更新条数为0");
                }
            } else {
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                throw new ServiceException("只允许操作申请中的案卷");
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public String importArchives(List<RecordArchives> archivesList, String operName) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        if (StringUtils.isNull(archivesList) || archivesList.size() == 0) {
            throw new ServiceException("导入案卷数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (RecordArchives archives : archivesList) {
            try {
                BeanValidators.validateWithException(validator, archives);
                archives.setCreateBy(operName);
                this.insertRecordArchives(archives);
                successNum++;
                successMsg.append("<br/>" + successNum + "、案卷 " + archives.getCaseFileTitle() + " 导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、案卷 " + archives.getCaseFileTitle() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确或案卷名称重复，错误如下：");
            //手工回滚异常
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

}
